package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description: 登录页面，验证用户名和密码，创建会话
 */
@WebServlet("/blogLogin")
public class BlogLoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获得请求中的用户名和密码，用户名可能是中文
        // Servlet默认不是按照utf8进行编码，因此需要显式指定
        req.setCharacterEncoding("utf8");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        resp.setContentType("text/html; charset=utf8");
        // 判断用户名或密码是否为空
        if(userName == null || "".equals(userName) || passWord == null || "".equals(passWord)) {
            resp.getWriter().write("<h3>当前用户名或密码为空!<h3>");
            return;
        }
        // 在数据库中查找用户名是否存在，并比较密码是否相同
        UserDao userDao = new UserDao();
        User user= userDao.selectByName(userName);
        if(user != null && user.getPassWord().equals(passWord)) {
            // 用户名且密码正确，让浏览器的cookie中保存sessionId
            HttpSession session = req.getSession(true);
            session.setAttribute("user", user);
            // 重定向
            resp.sendRedirect("blog_list.html");
        }else {
            resp.getWriter().write("<h3>登录失败，用户名或密码错误!<h3>");
        }
    }

    // 这个方法是确认用户登录信息，如果在博客列表页和博客详情页显示未登录，则自动跳转到博客登录页
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        HttpSession session = req.getSession(false);
        // 没有会话
        if(session == null) {
            User user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");
        // 虽然存在会话但是会话中的user为空
        if(user == null) {
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        // 已经登录的状态
        user.setPassWord(null);
        UserDao userDao = new UserDao();
        int newCount = userDao.selectById(user.getUserId()).getBlogCount();
        user.setBlogCount(newCount);
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
